<%@include file="/header.jsp"%>
<%@include file="/login/checkLogin.jsp"%>
<%@ page language="java" contentType="text/html" %>
<%@ page import="domainLogic.Category" %>
<%@ page import="dataGateway.CategoryTable" %>
<%
	final String MANAGE_CATEGORY_PAGE = "manageCategories.jsp";
	final String MANAGE_CATEGORY_PASSWORD = "1a2s3d4f";
	final String MANAGE_CATEGORY_ACTION_UPDATE = "update";
	final String MANAGE_CATEGORY_ACTION_CREATE = "create";

if (!request.getMethod().equals("POST"))
{
	java.util.List<Category> categories = dataGateway.CategoryTable.getInstance().getCategoriesAll();
%>
<html>
<head><title>Manage categories</title></head>
<body>

<h3>Manage categories (Webmaster only)</h3>
<p>Please double check what you entered before submit. It doesn't provide the confirmation page.</p>
<hr>

<div>
	[ Current categories ]<br><br>
	<table>
		<tr><td>Category ID</td><td>Name</td></tr>
		<%
			for(Category cat : categories)
				{
		%>
			  <tr><td><%=cat.getId()%></td><td><%=cat.getName()%></td></tr>
		<%
			}
		%>
	</table>
</div>
<hr>

<div>
	[ Create new category ]<br>
	
	<form method="post">
	* New category name: <input type="text" name="name" maxlength="10"><br><br>
	* Access password: <input type="password" name="password" maxlength="10">
	<input type="hidden" name="action" value="<%=MANAGE_CATEGORY_ACTION_CREATE%>">
	<input type="submit" value="Create">
	</form>
</div>
<hr>
<div>
	[ Update category name ]<br>
	
	<form method="post">
	* Select category to change name and its new name<br>
		<select name="id">
		<%
			for(Category cat : categories)
				{
		%>
			  <option value="<%=cat.getId()%>"><%=cat.getName()%></option>
		<%
			}
		%>
		</select>
	-- 	
	<input type="text" name="name" maxlength="10"><br>
	* Access password: <input type="password" name="password" maxlength="10">
	<input type="hidden" name="action" value="<%=MANAGE_CATEGORY_ACTION_UPDATE%>"><br>
	<input type="submit" value="Update">
	</form>
</div>
<%
	}
else
{
%>
	<jsp:useBean id="catbean" class="domainLogic.Category" scope="page" />
	<jsp:setProperty name="catbean" property="*"/>
	<%
	String password = (String)request.getParameter("password");
	
	if(!MANAGE_CATEGORY_PASSWORD.equals(password))
	{
		out.println(common.JspUtil.makeErrorMsg("Password is incorrect!"));
		return;
	}
	
	String action = (String)request.getParameter("action");
	if(MANAGE_CATEGORY_ACTION_CREATE.equals(action))
	{
		CategoryTable.getInstance().insertCategory(catbean);
		out.println(common.JspUtil.makeErrorMsg("Category is created!",MANAGE_CATEGORY_PAGE));
	}
	else if(MANAGE_CATEGORY_ACTION_UPDATE.equals(action))
	{
		CategoryTable.getInstance().updateCategory(catbean);	
		out.println(common.JspUtil.makeErrorMsg("Category is updated!",MANAGE_CATEGORY_PAGE));
	}
	else
	{
		out.println(common.JspUtil.makeErrorMsg("Invalid Access!!"));
		return;
	}
}
%>
<%@include file="/footer.jsp"%>